axlib.use(['toast'], main);

function main(plugins) {
  let { toast } = plugins;
  let repData = THIS.getData();
  let exData = THIS.getExtraData({format:'row'});

  let bin = axlib.jsonbin({
    binId: String(exData['仓库ID'])
  });

  getSymbolData(repData);
  $axure('@box2').setPanelStateByName('State2');
  
  THIS.$repeater.on('REPEATER_DATA_UPDATED', (e, res) => {
    let name = res[4].value.match(/\"(\S*)\"/)[1];
    let action = res[1].value.text;
    if (name !== '数据操作') return;

    if (action === '读取') {
      toast({text:'正在下载数据,请耐心等待~', hideAfter:false});
      bin.read(res => {
        console.log(res.record.data);
        toast({text:'数据完成下载!', stack:1});
      });
    }

    if (action === '写入') {
      toast({text:'正在上传数据,请耐心等待~', hideAfter:false});
      bin.update({foo:'bar'}, res=>{
        console.log(res.record.data);
        toast({text:'数据上传完毕!', stack:1});
      });
    }

  });
}

function getSymbolData(list) {
  let arr = [];
  for (let i=0; i<list.length; i++) {
    let item = list[i];
    let symbolName = item.symbol;
    let enabled = item.enabled ?? 1;
    if (enabled === '0') continue;
    
    let symbolType = getSymbolType(symbolName);
    let symbol = $axure(`@${symbolName}`);
    let $symbol = symbol.$().eq(0);
    let symId = symbol.getId();
    let value;
    if (symbolType == 'shape') {
      value = $symbol.children('.text').html().trim();
    }
    else if (symbolType == 'dynamicPanel') {
      let stateDiv = symbol.getCurrentPanelState();
      let state = $(stateDiv).id();
      let id = Number(state.split('_state')[1]);
      console.log( symbolName, id );
    }
    else if (symbolType == 'dynamicPanel') {

    }
    // arr.push({sym, value});
  }
}

function getSymbolType(name) {
  let $el = $axure(`@${name}`).$();
  let type;
  if ($el.children('.panel_state').length>0) {
    type = 'dynamicPanel';
  }
  else if ($el.children('input').length>0 && $el.children('input').attr('type')== 'text') {
    type = 'textBox';
  }
  else if ($el.children('textarea').length>0) {
    type = 'textArea';
  }
  else if ($el.children('input').length>0 && $el.children('input').attr('type')== 'checkbox') {
    type = 'checkbox';
  }
  else if ($el.children('input').length>0 && $el.children('input').attr('type')== 'radio') {
    type = 'radio';
  }
  else if ($el.children('select').length>0 && $el.children('select').css('appearance')=='menulist-button') {
    type = 'dropList';
  }
  else if ($el.children('select').length>0) {
    type = 'listBox';
  }
  else if ($el.children('iframe').length>0 && $el.children().length==1) {
    type = 'iframe';
  }
  else if ($el.children('img').length>0 && $el.children().length==1) {
    type = 'image';
  }
  else if ($el.children('.text').length>0) {
    type = 'shape';
  }
  else if ($el.children().length==0) {
    type = 'hotSpot';
  }
  return type;
}